import boom from '@hapi/boom';
import { validationResult } from 'express-validator';

import { querySql } from '../db/mysql';
import { CODE_ERROR, CODE_SUCCESS } from '../utils/constant';

// 获取分类
export function getCategoryList(req, res, next){
    const queryStr:string = `select * from category`

    querySql(queryStr).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '成功',
            data
        })
    }).catch(err => {
        var error = new Error(err);
        next(boom.boomify(error, { statusCode: 501,message:'数据库异常' }));
    })
}

// 保存分类
export function saveCategory(req, res, next){
    const err:any = validationResult(req)
    console.log(err, 'err')
    if(!err.isEmpty()){
        const [{msg}] = err.errors;
        
        next(boom.badRequest(msg))
        return
    }
    const addSql:string = `INSERT INTO category SET name=?, iconName=?`;
    const {name, iconName} = req.body;
    querySql(addSql, [name, iconName]).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '保存成功'
        })
    }).catch(err => {
        var error = new Error(err);
        next(boom.boomify(error, { statusCode: 501,message:'数据库异常' }));
    })

}

// 更新分类
export function updateCategory(req, res, next){
    const {id} = req.params;
    if(!id){
        next(boom.badRequest('缺少id'))
        return
    }

    const err: any = validationResult(req)

    if(!err.isEmpty()){
        const [{msg}] = err.errors;
        
        next(boom.badRequest(msg))
        return
    }
    const {name, iconName} = req.body;
    const updateSql: string=`update category set name=?, iconName=? where idcategory=${id}`;
    querySql(updateSql, [name, iconName]).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '更新成功'
        })
    }).catch(err => {
        var error = new Error(err);
        next(boom.boomify(error, { statusCode: 501,message:'数据库异常' }));
    })

}

// 删除
export function delCategory(req, res, next){
    const {id} = req.params;
    console.log(id)
    if(!id){
        next(boom.badRequest('缺少id'))
        return
    }
    const delSql: string=`delete from category where idcategory=${id}`;
    querySql(delSql).then(data=> {
        res.json({
            code: CODE_SUCCESS,
            msg: '删除成功'
        })
    }).catch(err => {
        var error = new Error(err);
        next(boom.boomify(error, { statusCode: 501,message:'数据库异常' }));
    })

}